package com.zenithmind.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zenithmind.common.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 多租户字段自动填充处理器
 * 自动填充租户ID、创建人、修改人、创建时间、修改时间等字段
 * 
 * @author ZenithMind
 * @since 2024-06-30
 */
@Slf4j
@Primary
@Component("multiTenantMetaObjectHandler")
public class MultiTenantMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始插入填充...");
        
        // 填充租户ID
        String tenantId = UserContext.getTenantId();
        if (StringUtils.hasText(tenantId)) {
            this.strictInsertFill(metaObject, "tenantId", String.class, tenantId);
            log.debug("插入填充租户ID: {}", tenantId);
        }
        
        // 填充创建人
        String userId = UserContext.getUserId();
        if (StringUtils.hasText(userId)) {
            this.strictInsertFill(metaObject, "createBy", String.class, userId);
            log.debug("插入填充创建人: {}", userId);
        }
        
        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        
        // 填充修改人
        if (StringUtils.hasText(userId)) {
            this.strictInsertFill(metaObject, "updateBy", String.class, userId);
        }
        
        // 填充修改时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        // 填充逻辑删除字段
        this.strictInsertFill(metaObject, "isDeleted", Integer.class, 0);
        
        log.debug("插入填充完成");
    }

    /**
     * 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始更新填充...");
        
        // 填充修改人
        String userId = UserContext.getUserId();
        if (StringUtils.hasText(userId)) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, userId);
            log.debug("更新填充修改人: {}", userId);
        }
        
        // 填充修改时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        
        log.debug("更新填充完成");
    }
}
